package com.example.myapplication8.ui.sidebar

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.view.accessibility.AccessibilityManager
import android.accessibilityservice.AccessibilityServiceInfo
import android.content.ComponentName
import com.example.myapplication8.service.FloatingWindowService
import java.io.File

/**
 * 侧边栏管理器
 * 处理侧边栏相关的业务逻辑
 */
class SidebarManager private constructor(private val context: Context) {
    
    private var currentState: SidebarState = SidebarState.CLOSED
    private val stateListeners = mutableListOf<(SidebarState)-> Unit>()

    /**
     * 检查无障碍服务是否启用
     */
    fun isAccessibilityServiceEnabled(): Boolean {
        return try {
            val accessibilityManager = context.getSystemService(Context.ACCESSIBILITY_SERVICE) as? AccessibilityManager
                ?: run {
                    Log.e(TAG, "无法获取AccessibilityManager服务")
                    return false
                }

            val serviceComponentName = ComponentName(context.packageName, 
                "${context.packageName}.service.MyAccessibilityService")
            
            Log.d(TAG, "检查服务: ${serviceComponentName.flattenToString()}")
            
            // 方法1: 通过系统设置检查
            val enabledServicesString = Settings.Secure.getString(
                context.contentResolver,
                Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
            )
            Log.d(TAG, "系统已启用的服务: $enabledServicesString")
            
            if (enabledServicesString?.contains(serviceComponentName.flattenToString()) == true) {
                Log.i(TAG, "在系统设置中找到服务")
                return true
            }
            
            // 方法2: 通过AccessibilityManager检查
            val runningServices = accessibilityManager.getEnabledAccessibilityServiceList(
                AccessibilityServiceInfo.FEEDBACK_ALL_MASK
            )
            
            Log.d(TAG, "当前运行的无障碍服务数量: ${runningServices.size}")
            runningServices.forEach { service ->
                Log.d(TAG, "运行中的服务: ${service.id}")
            }
            
            val isEnabled = runningServices.any { 
                try {
                    val matches = it.id.contains(serviceComponentName.flattenToString())
                    if (matches) {
                        Log.i(TAG, "服务正在运行: ${it.id}")
                    }
                    matches
                } catch (e: Exception) {
                    Log.e(TAG, "检查服务ID时出错: ${e.message}")
                    false
                }
            }
            
            if (!isEnabled) {
                Log.w(TAG, "未找到运行中的服务")
            }
            
            isEnabled
        } catch (e: Exception) {
            Log.e(TAG, "检查无障碍服务状态时出错: ${e.message}")
            e.printStackTrace()
            false
        }
    }

    /**
     * 检查悬浮窗权限
     */
    fun hasOverlayPermission(): Boolean {
        return Settings.canDrawOverlays(context)
    }

    /**
     * 启动前台服务
     */
    fun startForegroundService() {
        try {
            val serviceIntent = Intent(context, FloatingWindowService::class.java)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                context.startForegroundService(serviceIntent)
            } else {
                context.startService(serviceIntent)
            }
        } catch (e: Exception) {
            Log.e("SidebarManager", "Error starting foreground service: ${e.message}")
            throw e
        }
    }

    /**
     * 停止前台服务
     */
    fun stopForegroundService() {
        try {
            val serviceIntent = Intent(context, FloatingWindowService::class.java)
            context.stopService(serviceIntent)
        } catch (e: Exception) {
            Log.e("SidebarManager", "Error stopping foreground service: ${e.message}")
            throw e
        }
    }

    /**
     * 获取版本信息
     */
    fun getVersionInfo(): String {
        return try {
            val packageInfo = context.packageManager.getPackageInfo(context.packageName, 0)
            val versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                packageInfo.longVersionCode
            } else {
                @Suppress("DEPRECATION")
                packageInfo.versionCode.toLong()
            }
            "v${packageInfo.versionName} (${versionCode})"
        } catch (e: Exception) {
            Log.e("SidebarManager", "Error getting version info: ${e.message}")
            "Unknown"
        }
    }

    /**
     * 获取运行日志
     */
    fun getRunningLog(): String {
        return try {
            val logFile = File(context.getExternalFilesDir(null), "app.log")
            if (logFile.exists()) {
                logFile.readText()
            } else {
                "暂无日志"
            }
        } catch (e: Exception) {
            Log.e("SidebarManager", "Error reading log file: ${e.message}")
            "无法读取日志"
        }
    }

    /**
     * 清除运行日志
     */
    fun clearRunningLog() {
        try {
            val logFile = File(context.getExternalFilesDir(null), "app.log")
            if (logFile.exists()) {
                logFile.delete()
            }
        } catch (e: Exception) {
            Log.e("SidebarManager", "Error clearing log file: ${e.message}")
            throw e
        }
    }

    /**
     * 获取QQ群链接
     */
    fun getQQGroupUrl(): String {
        return "mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26jump_from%3Dwebapi%26k%3D905933253"
    }

    /**
     * 获取QQ群号
     */
    fun getQQGroupNumber(): String {
        return "2818467225"
    }

    fun openDrawer() {
        try {
            if (currentState != SidebarState.OPEN) {
                currentState = SidebarState.OPEN
                notifyStateChanged()
            }
        } catch (e: Exception) {
            Log.e("SidebarManager", "Error opening drawer: ${e.message}")
        }
    }

    fun closeDrawer() {
        try {
            if (currentState != SidebarState.CLOSED) {
                currentState = SidebarState.CLOSED
                notifyStateChanged()
            }
        } catch (e: Exception) {
            Log.e("SidebarManager", "Error closing drawer: ${e.message}")
        }
    }

    fun toggleDrawer() {
        try {
            currentState = when (currentState) {
                SidebarState.OPEN -> SidebarState.CLOSED
                SidebarState.CLOSED -> SidebarState.OPEN
            }
            notifyStateChanged()
        } catch (e: Exception) {
            Log.e("SidebarManager", "Error toggling drawer: ${e.message}")
        }
    }

    fun addStateListener(listener: (SidebarState) -> Unit) {
        try {
            if (!stateListeners.contains(listener)) {
                stateListeners.add(listener)
            }
        } catch (e: Exception) {
            Log.e("SidebarManager", "Error adding state listener: ${e.message}")
        }
    }

    fun removeStateListener(listener: (SidebarState) -> Unit) {
        try {
            stateListeners.remove(listener)
        } catch (e: Exception) {
            Log.e("SidebarManager", "Error removing state listener: ${e.message}")
        }
    }

    private fun notifyStateChanged() {
        try {
            stateListeners.forEach { listener ->
                try {
                    listener(currentState)
                } catch (e: Exception) {
                    Log.e("SidebarManager", "Error notifying listener: ${e.message}")
                }
            }
        } catch (e: Exception) {
            Log.e("SidebarManager", "Error notifying state change: ${e.message}")
        }
    }

    enum class SidebarState {
        OPEN,
        CLOSED
    }

    companion object {
        private const val TAG = "SidebarManager"
        @Volatile
        private var instance: SidebarManager? = null

        fun getInstance(context: Context): SidebarManager {
            return instance ?: synchronized(this) {
                instance ?: SidebarManager(context.applicationContext).also { instance = it }
            }
        }
    }
} 